<?php

namespace App\Lib;

use EasySwoole\FastCache\Cache;

/**
 * 微信通用接口
 */
class WeChat
{
    /**
     * 生成的唯一性key
     * @param string $str
     * @return string
    */
    public static function getFileKey($str)
    {
        return substr(md5(self::makeRandomString() . $str . time() . rand(0, 9999)), 8, 16);
    }

    /**
     * 获取微信ticket
     * @param  [type]  $wx_appid  [description]
     * @param  [type]  $wx_secret [description]
     * @param  integer $times     [description]
     * @param  integer $lt        [description]
     * @return [type]             [description]
     */
    public static function wx_uniqid_api_ticket($wx_appid, $wx_secret, $times=1, $lt=1800)
    {
        $key = 'wx_uniqid_jsapi_ticket_' . $wx_appid;
        $at = Cache::getInstance()->get($key);
        if ($at && (!is_array($at))) {
            $at=json_decode($at, true);
        }
        if (is_array($at) && ((time()-$at['ctime']) < ($at['expires_in'] - $lt))) { //失效前?秒,从新获取
            return $at['ticket'];
        }
        $access_token = self::wx_uniqid_access_token($wx_appid, $wx_secret);
        $temp = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";

        $curl = new Curl();
        $temp = $curl->request('GET', $temp);

        // $temp = $this->curl_request($temp);
        $at =json_decode($temp, true);
        if (isset($at['ticket']) && isset($at['errmsg']) && ($at['errmsg'] == 'ok')) { //获取到
            $at['ctime'] = time();
            Cache::getInstance()->set($key, json_encode($at));
            return $at['ticket'];
        } else {
            //删除缓存
            $errmsg = 'times '.$times.'; fetch wx_uniqid_jsapi_ticket fail; ' . json_encode(['r'=>$temp]);

            if ($times<3) { //从新尝试2次
                $times++;
                self::wx_uniqid_api_ticket($wx_appid, $wx_secret, $times);
            }
            return 0;
        }
    }

    /**
     * 获取微信token
     * @param  [type]  $wx_appid  [description]
     * @param  [type]  $wx_secret [description]
     * @param  integer $times     [description]
     * @param  integer $lt        [description]
     * @param  integer $ftype     [description]
     * @param  integer $sid       [description]
     * @return [type]             [description]
     */
    public static function wx_uniqid_access_token($wx_appid, $wx_secret, $times=1, $lt=60, $ftype=1, $sid=0)
    {
        $key = 'wx_uniqid_access_token_' . $wx_appid;
        $at = Cache::getInstance()->get($key);
        if ($at && (!is_array($at))) {
            $at=json_decode($at, true);
        }
        if (is_array($at) && ((time()-$at['ctime']) < ($at['expires_in'] - $lt))) { //失效前?秒,从新获取
            return $at['access_token'];
        }
        $temp = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $wx_appid . "&secret=" . $wx_secret;

        $curl = new Curl();
        $temp = $curl->request('GET', $temp);

        // $temp = $this->curl_request($temp);
        $at = json_decode($temp, true);
        if (isset($at['access_token'])) { //获取到
            $at['ctime'] = time();
            Cache::getInstance()->set($key, json_encode($at));
            return $at['access_token'];
        } else {
            $errmsg = 'times '.$times.'; fetch access_token fail; ' . json_encode(['r'=>$temp]) . '; appid: ('.$wx_appid.'); secret: ('. $wx_secret . ')';
            if ($times<3) { //从新尝试2次
                $times++;
                self::wx_uniqid_access_token($wx_appid, $wx_secret, $times);
            }
            return 0;
        }
    }


    public static function pushmsg($postdata, $wx_appid, $wx_secret)
    {
        //获取token
        $at = self::wx_uniqid_access_token($wx_appid, $wx_secret);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$at;
        $pdata = json_encode($postdata);
        //发送数据
        $curl = new Curl();
        $res = $curl->request('POST', $url, $pdata);

        $result = json_decode($res, true);
        //判断是否发送成功
        if (isset($result['errmsg'])) {
            if ($result['errmsg'] == 'ok') {
                return 'ok';
            } else {
                //发送失败
                $errmsg = 'pushmsg_errmsg: '. json_encode($result);
                $errmsg = $errmsg . " ; re_time: ".time()." ; send_access_token: [".$at."]";
                return $result['errmsg']; //腾讯返回的错误提示
            }
        } else {
            $errmsg = 'pushmsg_fail; ' . json_encode(['r'=>$url]);
            return '提交失败';
        }
    }
}
